package com.liwenfeng.huangputi;

import com.liwenfeng.domain.Order;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/*
 * 1.定义订单类Order，创建ArrayList集合，用于存储订单order对象（解析XML 4分，封装成对象2分）
 * 2.使用Stream流找出今天之前的订单，并遍历。3分
 * 3.使用Stream流找出价格最贵的订单，打印出来。3分
 * 4.使用Stream流遍历，按照价格降序输出订单详情。3分
 * */
public class XmlReader {
    public static void main(String[] args) throws DocumentException {
        ArrayList<Order> orders = new ArrayList<>();
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(XmlReader.class.getResourceAsStream("/orders.xml"));
        Element root = document.getRootElement();
        List<Element> orderEles = root.elements();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (Element orderEle : orderEles) {
            Order order = new Order();
            order.setId(Integer.parseInt(orderEle.attributeValue("id")));
            order.setName(orderEle.elementText("name"));
            order.setTime(LocalDateTime.parse(orderEle.elementText("time"), dtf));
            order.setPrice(Double.parseDouble(orderEle.elementText("double")));
            orders.add(order);
        }
        orders.forEach(System.out::println);

        System.out.println("2023-11-21之前的订单为：---------------------------");
        orders.stream().filter(item -> item.getTime().isBefore(LocalDateTime.parse("2023-11-21 00:00:00", dtf))).forEach(System.out::println);

        System.out.println("最贵的订单为：---------------------------");
        orders.stream().max(Comparator.comparingDouble(Order::getPrice)).ifPresent(System.out::println);

        System.out.println("按价格降序排序：---------------------------");
        orders.stream().sorted(Comparator.comparingDouble(Order::getPrice).reversed()).forEach(System.out::println);
    }
}
